<?php

namespace App\Http\Validate\OpenShop\InvestmentPromotion;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserContractEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserOrderEnum;
use App\Http\Validate\BaseValidate;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use Closure;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;

/**
 * [ open_shop_user_contract 招商加盟 - 合同 ] - 校验规则
 *
 * @OpenShopUserContractValidate
 * @package App\Http\Controllers
 * @date 2022/03/01 02:35:56
 * @author GreenLeaf <786407418@qq.com>
 */
class UserContractValidate extends BaseValidate
{

    public static function registerValidateRules(): void
    {
        // TODO: Implement registerValidateRules() method.
    }

    /**
     * 预处理参数
     *
     * @param array $data
     * @return array
     */
    public static function beforeValidate(array $data): array
    {
        $data = collect($data)->filter(function ($v) {
            if ($v === "") {
                return false;
            }
            return true;
        })->toArray();
        return parent::beforeValidate($data); // TODO: Change the autogenerated stub
    }

    /**
     * 获取规则信息
     *
     * @param array $fields
     * @return string[]
     */
    public static function getRules(array $fields = []): array
    {
        return self::getActuallyRules([
            'orderNo'                 => 'bail|required|exists:' . OpenShopUserContractModel::class . ',OrderNo',
            //
            'contractors'             => 'bail|required|in:' . implode(",",
                    array_keys((UserContractEnum::CONTRACTORS))),
            //签约主题  0 ： 个人 1 ： 公司
            'companyName'             => 'exclude_unless:contractors,' . UserContractEnum::CONTRACT_COMPANY . '|bail|required|string:max:60',
            //公司名称
            'businessLicenseNumber'   => 'exclude_unless:contractors,' . UserContractEnum::CONTRACT_COMPANY . '|bail|required|string|max:60',
            //营业执照号
            'address'                 => 'exclude_unless:contractors,' . UserContractEnum::CONTRACT_COMPANY . '|bail|required|string|max:255',
            //地址
            'legalPerson'             => 'exclude_unless:contractors,' . UserContractEnum::CONTRACT_COMPANY . '|bail|required|string|max:255',
            //法人姓名
            'businessLicenseImg'      => 'exclude_unless:contractors,' . UserContractEnum::CONTRACT_COMPANY . '|bail|required|string|max:255',
            //阿里云返回的数据
            'businessLicenseContent'  => 'exclude_unless:contractors,' . UserContractEnum::CONTRACT_COMPANY . '|bail|required|string',
            //营业执照号
            'startTime'               => 'bail|required|date_format:Y-m-d',
            //合同开始时间
            'endTime'                 => 'bail|required|date_format:Y-m-d|after:startTime',
            //合同截止时间
            'contractType'            => 'bail|required|in:' . implode(",",
                    array_keys((UserContractEnum::CONTRACT_TYPE))),
            //签约类型  0 ： 新店加盟 1 ： 老店裂变
            'policyTemplateId'        => 'bail|required|integer|exists:' . OpenShopContractTemplateModel::class . ',id',
            //政策模版id
            'remark'                  => 'sometimes|required|max:999',
            //内部备注
            'year'                    => 'bail|required|max:100|min:1',
            //合同年限
            'initialFee'              => 'bail|required|integer|min:0',
            //加盟费
            'technologyTransferFee'   => 'bail|required|integer|min:0',
            //技术转让费
            'deposit'                 => 'bail|required|integer|min:0',
            //保证金
            'managementCost'          => 'bail|required|integer|min:0',
            //特许权使用费第一年
            'managementCostEveryYear' => 'bail|required|integer|min:0',
            //特许权使用费每年
            'decorationDeposit'       => 'bail|required|integer|min:0',
            //装修保证金
            'shopCount'               => 'bail|required|integer|min:1|max:100',
            //店铺数量
            'provideShopCode'         => 'bail|sometimes|regex:/\d+/|min:1',
            'version'                 => '',
            //版本号
            'operateSubsidyAmount'    => 'sometimes|int|min:0',
            'kindSubsidyAmount'       => 'sometimes|int|min:0',
            //加盟模式 1-传统模式 2分账模式 3定金模式
            'mode'                    => 'bail|in:' . implode(",", array_keys((OpenShopContractTemplateModel::MODE_MAP_TEXT))),
            //分账模式信息-抽佣比例配置
            'content'                 => 'bail|array',
            //邀请人id
            'inviterId'               => 'bail|string|max:20|min:1',
            //邀请人名称
            'inviterName'             => 'bail|string|max:50|min:1',
            //部门名称
            'departmentName'          => 'bail|string|max:120|min:1',
            // 分账模式：每月实收抽佣比例
            'depositAmountRatio'=>'bail|numeric|regex:/^\d+(\.\d{1,2})?$/',
            // 分账模式：月实收抽佣封顶金额（元）
            'monthRealAmountCommissionCapping'=>'bail|integer|min:0',
            // 分账模式：是否抽佣累计封顶 0/1
            'isCommissionCapping'=>'bail|integer|in:0,1',
            // 分账模式：抽佣累计封顶金额（元）
            'amountCommissionCapping'=>'bail|integer|min:0',
            // 定金模式：定金金额
            'depositAmount'=>'bail|integer|min:0',


        ],
            $fields);
    }

    public static array $validateMsg = [
        'orderNo.exists' => '无效的订单',
        "orderNo.unique" => "当前订单合同已存在"
    ];


    public static array $attributes = [
        'orderNo'                          => '订单号',
        'contractors'                      => '签约主体',
        'companyName'                      => '公司名称',
        'businessLicenseImg'               => '营业执照',
        'businessLicenseNumber'            => '营业执照号',
        'address'                          => '公司地址',
        'legalPerson'                      => '法人姓名',
        'startTime'                        => '合同开始时间',
        'endTime'                          => '合同截止时间',
        'contractType'                     => '签约类型',
        'policyTemplateId'                 => '政策模版id',
        'remark'                           => '内部备注',
        'initialFee'                       => '加盟费',
        'technologyTransferFee'            => '技术转让费',
        'deposit'                          => '保证金',
        'managementCost'                   => '特许权使用费第一年',
        'decorationDeposit'                => '装修保证金',
        'shopCount'                        => '店铺数量',
        'year'                             => '合同年限',
        'mode'                             => '加盟模式',
        'content'                          => '分账模式信息',//抽佣比例配置
        'inviterId'                        => '邀请人id',
        'inviterName'                      => '邀请人名称',
        'departmentName'                   => '部门名称',
        'depositAmountRatio'               => '每月实收抽佣比例', // 分账模式
        'monthRealAmountCommissionCapping' => '月实收抽佣封顶金额', // 分账模式
        'isCommissionCapping'              => '是否抽佣累计封顶', // 分账模式
        'amountCommissionCapping'          => '抽佣累计封顶金额', // 分账模式
        'depositAmount'                    => '定金金额', // 定金模式
    ];

    /**
     * @return Closure
     */
    public static function getInsertOrUpdateHandleParams(): Closure
    {
        return function ($params) {
            $params['startTime']          = strtotime($params['startTime']);
            $params['endTime']            = strtotime($params['endTime']);
            $params['remark']             = empty($params['remark']) ? null : $params['remark'];
            $fields                       = array_merge(OpenShopSignOrderModel::ORDER_SHOULD_PRICE_FROM,
                ["managementCostEveryYear"]);
            $params["businessLicenseImg"] = getPrivateFileKey($params['businessLicenseImg'] ?? '');
            if (isset($params['content']) && $params['content'] && is_array($params['content'])) {
                $params['content'] = json_encode($params['content']);
            } else {
                $params['content'] = null;
            }

            return array_merge(
                $params,
                OpenShopContractTemplateModel::query()
                                             ->where('id', $params['policyTemplateId'])
                                             ->get()->each(function (&$item) use ($fields) {
                        collect($fields)->each(function ($v) use (&$item) {
                            $item->{$v} = $item->{$v} * ($item->shopCount ?? 1);
                        });
                    })->getIterator()->current()->only($fields)
            );
        };
    }

    /**
     * 创建校验
     *
     * @param array $requestParams
     * @return array
     * @throws ValidationException
     */
    public static function insertValidate(array $requestParams): array
    {
        return self::baseValidate(
            $requestParams,
            collect(self::getRules())->except(['orderNo'])->keys()->toArray(),
            self::getInsertOrUpdateHandleParams(),
            [
                'orderNo' => [
                    'required',
                    Rule::unique('open_shop_user_contract', 'orderNo'),
                    Rule::exists('open_shop_sign_order')->where(function ($query) {
                        $query->where('status', UserOrderEnum::STATUS_NORMAL);
                    })
                ]
            ],
            self::getValidateMsg()
        );
    }

    /**
     * 更新校验
     *
     * @param array $requestParams
     * @return array
     * @throws ValidationException
     */
    public static function updateValidate(array $requestParams): array
    {
        return self::baseValidate(
            $requestParams,
            collect(self::getRules())->except(['orderNo'])->keys()->toArray(),
            self::getInsertOrUpdateHandleParams(),
            [
                'orderNo' => [
                    'required',
                    Rule::exists('open_shop_user_contract', 'orderNo'),
                    Rule::exists('open_shop_sign_order', 'orderNo')->where(function ($query) {
                        $query->where('status', '!=', SignOrderEnum::ORDER_STATUS_NO);
                    })
                ]
            ],
            self::getValidateMsg()
        );
    }

    /**
     * 详情校验
     *
     * @param array $requestParams
     * @return array
     * @throws ValidationException
     */
    public static function detailValidate(array $requestParams): array
    {
        return self::baseValidate($requestParams, ['orderNo']);
    }


    /**
     * 作废合同校验
     *
     * @param array $requestParams
     * @return array
     * @throws ValidationException
     */
    public static function invalidContractValidate(array $requestParams): array
    {
        return self::baseValidate(
            $requestParams,
            ['orderNo'],
            null,
            [
                'orderNo' => [
                    "required",
                    "string",
                    Rule::exists("open_shop_user_contract", "orderNo")
                ]
            ]
        );
    }
}
